package photosalvage.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Stage;
import com.google.inject.servlet.GuiceServletContextListener;

public class ContextListener extends GuiceServletContextListener {

	public static final String STAGE = "photosalvage.stage";

	private ServletContext servletContext;
	private Stage stage = Stage.DEVELOPMENT;
	private Injector injector;

	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		this.servletContext = servletContextEvent.getServletContext();
		String stageName = servletContext.getInitParameter(STAGE);
		if (stageName != null) {
			Stage stage_ = Stage.valueOf(stageName);
			if (stage_ != null) {
				this.stage = stage_;
			}
		}
		initInjector();
		super.contextInitialized(servletContextEvent);
		servletContext.setAttribute(Injector.class.getName(), injector);
	}

	@Override
	protected Injector getInjector() {
		return injector;
	}

	protected void initInjector() {
		injector = Guice.createInjector(stage,
				new PhotoSalvageModule(servletContext));
	}
}
